function PBMcleanupScript () {
    var jsonScript = document.getElementById('po_pmb_google_script');
    if (jsonScript) {
        jsonScript.parentNode.removeChild(jsonScript);
    }
}

function PBMpayTaxCancel () {
    var cont = document.getElementById ('pbm_pay_tax_container');
    cont.innerHTML = "<a style='color:lime;' href='javascript:PBMpayTaxConfirm();void(0);'>Pay the tax now</a>";
}

function PBMpayTaxConfirm () {
    var cont = document.getElementById ('pbm_pay_tax_container');
    cont.innerHTML = "<a style='color:lime;' href='javascript:PBMpayTax();void(0);'>Yes, pay now</a>&nbsp;\
                     <a style='color:orange;' href='javascript:PBMpayTaxCancel();void(0);'>Cancel</a>";
}

function PBMpayTax () {
    var cont = document.getElementById ('pbm_pay_tax_container');
    var taxManager = document.getElementById("pbm_tax_manager").textContent;
    var taxAlly = document.getElementById("pbm_tax_ally").textContent;
    var amount = document.getElementById("pbm_tax_amount").textContent;
    var loc = localStorage.getItem ('po_pbm_base_coords');
    var pilot = POgetUserName();
    var place = PBMplace ();

    var viaPilot = null;
    var query = null;
    var msg = "PFC SB Tax has been sent by " + pilot;
    var reason = "PFC Tax: " + loc + ", " + pilot
    if (place == "transfer") {
        viaPilot = PBMgetViaPilot ();
        msg += " via "+viaPilot+". ";
        reason += ", via " + viaPilot;
    } else {
        msg += " to the Alliance Fund. ";
    }
    msg += "Amount sent: " + amount + " cr. SB location: " + loc;
    
    // Pay the tax
    PBMpayTaxTransaction (amount, reason);
    
    // Inform the tax manager and the Via Pilot
    POsendMsg (taxManager, "PFC SB Tax", msg, true);
    if (viaPilot) {
        msg += "\n\nPlease forward the money you received to the "+taxAlly+"'s Alliance Fund. The Tax manager, "+taxManager+", is awaiting the transaction.";
        msg += "\n\nPlease enter the following information into the payment description:\n";
        msg += reason;
        POsendMsg (viaPilot, "PFC SB Tax", msg, true);
    }
    
    // Submit the tax sheet entry
    PBMsubmitTaxEntry (loc, pilot, amount, viaPilot);
    
    cont.innerHTML = "<span style='color:lime;'>Thank you for your contribution!</span>";
}

function PBMpayTaxTransaction (amount, reason) {
    var place = PBMplace ();
    if (place == "alliance") {
        var url = "myalliance.php";
        var query = "credits="+amount+"&reason="+reason;
    } else {
        var url = "ship2ship_transfer.php";
        var playerid = document.getElementsByName("playerid")[0].value;
        var query = "credits="+amount+"&playerid="+playerid+"&transfer=to_other_ship";
    }
    POajaxPost (url, "POST", query);
}

function PBMsubmitTaxEntry (loc, pilot, amount, viaPilot) {
    var str = "formkey="+localStorage.getItem ("po_pbm_form_url")+
              "&entry.0.single=" + loc+
              "&entry.1.single=" + pilot+
              "&entry.2.single=" + amount;
    if (viaPilot) {
        str += "&entry.3.single=" + viaPilot;
    }
    str += "&submit=Submit";
    var url = "https://spreadsheets.google.com/spreadsheet/formResponse";
    POajaxPost (url, "POST", str);
}

function PBMvalidatePilotProfile (resp, taxAlly) {
    var cont = document.getElementById ('pbm_pay_tax_container');
    var ally = resp.split ("Alliance:")[1].split("<font")[1].split(">")[1].split("<")[0];

    if (ally == taxAlly) {
        cont.innerHTML = "<a style='color:lime;' href='javascript:PBMpayTaxConfirm();void(0);'>Pay the tax now</a>";
    } else {
        cont.innerHTML = "<span style='color:red;'>You can only pay the PFC SB tax via<br>member of the "+taxAlly+" alliance.</span>";
    }
}

function PBMvalidateViaPilot (taxAlly) {
    var playerid = document.getElementsByName("playerid")[0].value;
    var url = "profile.php";
    var query = "id="+playerid;
    var cont = document.getElementById ('pbm_pay_tax_container');
    cont.innerHTML = "<span style='color:orange'>verifying...</span>";
    
    POajaxPost (url, "GET", query, function (request) {
        if (request.readyState != 4) return;
        if (request.status == 200) {
            PBMvalidatePilotProfile (request.responseText, taxAlly);
        } else {
            cont.innerHTML = "<span style='color:red'>Pilot's alliance can't be verified. Are you sure to pay the tax anyway?</span><br>\
                            <a style='color:lime;' href='javascript:PBMpayTax();void(0);'>Yes, pay now</a>&nbsp;\
                            <a style='color:orange;' href='javascript:PBMpayTaxCancel();void(0);'>Cancel</a>";
        }
    });
}

function PBMshowMoney (resp) {
    var credits = Number(resp.split ("credits_current\'>")[1].split("<")[0].replace(/,/g, ""));
    var panel = document.getElementById ('pbm_sb_info_table');
    var tax = Number(document.getElementById ('pbm_tax_amount').textContent);
    var taxAlly = document.getElementById ('pbm_tax_ally').textContent;
    
    var str = "<tr style='color:orange; font-weight:bold'><td>Your money</td><td id='pbm_money_amount' align='right'>"+credits+"</td></tr>";
    if (credits < tax) {
        str += "<tr><td colspan=2 style='color:red;' align=center>You don't have enough<br>credits to pay the tax</td></tr>";
    } else {
        var place = PBMplace();
        if (place != "overview") {
            if (place == "alliance") {
                var myAlly = PBMgetAlly ();
                if (myAlly != taxAlly) {
                    str += "<tr><td colspan=2 style='color:red;' align=center>Please use the form in ship2ship transfer screen.<br>You have to transfer the money to a member<br>of the tax collecting alliance.</td></tr>";
                } else {
                    str += "<tr><td colspan=2 align=center id='pbm_pay_tax_container'><a style='color:lime;' href='javascript:PBMpayTaxConfirm();void(0);'>Pay the tax now</a></td></tr>";
                }
            } else {
                str += "<tr><td colspan=2 align=center id='pbm_pay_tax_container'><a style='color:lime;' href='javascript:PBMvalidateViaPilot(\""+taxAlly+"\");void(0);'>Verify target pilot's alliance</a></td></tr>";
            }
        } else {
            str += "<tr><td colspan=2 style='color:red;' align=center>Go to alliance page<br>or ship2ship transfer<br>page to pay the tax.</td></tr>";
        } 
    }
    
    panel.innerHTML += str;
}

function PBMrefreshMoney () {
    POajaxPost ("overview_stats.php", "get", "", function (request) {
        if (request.readyState != 4) return;
        if (request.status == 200) {
            PBMshowMoney (request.responseText);
        }
    });
}

function PBMshowBasePlan (data) {
    var panel = document.getElementById ('pbm_sb_info_table');
    var loc = localStorage.getItem ('po_pbm_base_coords');
    var str = "";
    
    var entries = data.feed.entry;
    var done = 0;
    for (var i=0; i<entries.length; i++) {
        var entry = entries[i];
        if (entry.content.$t == loc) {
            str += "<tr><td style='font-weight:bold;'>Economy</td><td>"+entries[i+4].content.$t+"</td></tr>";
            str += "<tr><td style='font-weight:bold;'>Stage</td><td>"+entries[i+7].content.$t+"</td></tr>";
            str += "<tr><td style='font-weight:bold;'>Population</td><td>"+entries[i+15].content.$t+"</td></tr>";
            str += "<tr><td colspan=2><hr></td></tr>";
            str += "<tr><td style='font-weight:bold;'>F price</td><td>"+entries[i+9].content.$t+" cr</td></tr>";
            str += "<tr><td style='font-weight:bold;'>W price</td><td>"+entries[i+10].content.$t+" cr</td></tr>";
            str += "<tr><td style='font-weight:bold;'>E price</td><td>"+entries[i+11].content.$t+" cr</td></tr>";
            str += "<tr><td colspan=2><hr></td></tr>";
            str += "<tr style='color:orange; font-weight:bold'><td>Tax</td><td id='pbm_tax_amount' align='right'>"+entries[i+13].content.$t+"</td></tr>";
            done ++;
        } else if (entry.content.$t == "Tax manager") {
            var taxManager = entries[i+1].content.$t;
            str = "<tr><td style='font-weight:bold;'>Tax manager</td><td id='pbm_tax_manager'>"+taxManager+"</td></tr>\
                  <tr><td colspan=2><hr></td></tr>" + str;
            done ++;
        } else if (entry.content.$t == "Tax alliance") {
            var taxAlly = entries[i+1].content.$t;
            str = "<tr><td colspan=2 align=center style='font-weight:bold;'>Tax collected by</td></tr>\
                  <tr><td colspan=2 align=center style='color:orange' id='pbm_tax_ally'>"+taxAlly+"</td></tr>" + str;
            done ++;
        }
        if (done == 3) break;
    }
    panel.innerHTML += str;
    PBMrefreshMoney ();
}

function PBMrefreshBasePlan () {
    var key = localStorage.getItem ("po_pbm_definition_url");
    PBMcleanupScript ();
    
    // Create the script node
    // Look here for details: http://stackoverflow.com/questions/2924563/access-google-apps-public-spreadsheet-via-javascript
    var script = document.createElement('script');
    script.setAttribute('src', 'https://spreadsheets.google.com/feeds/cells'
                         + '/' + key 
                         + '/2/public/values' + '?alt=json-in-script&callback=PBMshowBasePlan');
    script.setAttribute('id', 'po_pmb_google_script');
    script.setAttribute('type', 'text/javascript');
    document.documentElement.firstChild.appendChild(script);
}

function PBMshowSBPlan () {
    var panel = document.getElementById ('pbm_sb_plan_panel');
    if (panel.style.display == "block") {
        panel.innerHTML = "";
        panel.style.display = "none";
        return;
    }
    
    panel.style.display = "block";
    var loc = localStorage.getItem ("po_pbm_base_coords");
    if (!loc || loc.length==0) {
        panel.innerHTML = "<a href='starbase_overview.php'>SB Location is not set. Visit the SB Overview first to fetch the SB location.</a>";
        return;
    }
    panel.innerHTML = "<table><tbody id='pbm_sb_info_table'>\
                      </tr><th colspan=2 id='pbm_sb_location'>"+loc+"</th></tr>\
                      </tbody></table>";
    PBMrefreshBasePlan ();
}

function PMBcreateLink () {
    var div = document.createElement ("div");
    div.innerHTML = "<div><a href='javascript:PBMshowSBPlan();void(0);' style='color:lime'>Show SB Plan</a>\
                    <div id='pbm_sb_plan_panel' style='border:2px solid lime; display:none;'></div>\
                    </div>";
    return div.firstChild;
}

function PBMinstallLink () {
    var lnk = PMBcreateLink ();
    var place = PBMplace ();
    
    if (place == "overview") {
        var ths = document.getElementsByTagName ("th");
        for (var i=0; i<ths.length; i++) {
            if (ths[i].textContent == "Trade") {
                var myrow = document.createElement ("tr");
                var mycell = document.createElement ("td");
                myrow.appendChild (mycell);
                mycell.setAttribute ("align", "center");
                mycell.appendChild (lnk);
                var tr = ths[i].parentNode;
                tr.parentNode.insertBefore (myrow, tr);
                break;
            }
        }
    } else if (place == "alliance") {
        var ths = document.getElementsByTagName ("th");
        for (var i=0; i<ths.length; i++) {
            if (ths[i].textContent == "Leader") {
                var par = ths[i].parentNode.parentNode.parentNode.parentNode;
                par.parentNode.insertBefore (lnk,par);
                break;
            }
        }
    } else if (place == "transfer") {
        var ths = document.getElementsByTagName ("a");
        for (var i=0; i<ths.length; i++) {
            if (ths[i].textContent == "Return to the player menu") {
                var par = ths[i].parentNode;
                par.parentNode.insertBefore (lnk,par);
                break;
            }
        }
    }
}

function PBMgetAlly () {
    var fnts = document.getElementsByTagName ("font");
    for (var i=0; i<fnts.length; i++) {
        if (fnts[i].getAttribute ("size") == "5") return fnts[i].textContent;
    }
    return null;
}

function PBMplace () {
    var url = document.URL;
    if (document.URL.indexOf ("overview_sb.php") != -1) {
        return "overview";
    } else if (document.URL.indexOf ("myalliance.php") != -1) {
        return "alliance";
    } else if (document.URL.indexOf ("ship2ship_transfer.php") != -1) {
        return "transfer";
    }
    return "";
}

function PBMgetViaPilot () {
    var par = document.getElementsByTagName ("form")[0].parentNode;
    var str = par.firstChild.textContent;
    return str.split("wants to trade with ")[1].split(",")[0];
}

window.onload = PBMinstallLink;